package com.yu.app.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.service.WxPayService;
import com.yu.app.pojo.dto.OrderInfoDTO;
import com.yu.app.pojo.form.CreateOrderParams;
import com.yu.app.pojo.vo.HistoryOrderVO;
import com.yu.app.service.impl.OrderServiceImpl;
import com.yu.app.common.annotation.NeedLogin;
import com.yu.common.exception.ServiceException;
import com.yu.common.util.result.R;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.data.annotation.ReadOnlyProperty;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Api(tags = "订单服务")
@RestController
@Slf4j
@RequestMapping("/api-app/order")
public class OrderController {

    @Resource
    private OrderServiceImpl orderService;
    @Resource
    private WxPayService wxPayService;

    @ApiModelProperty("下订单")
    @NeedLogin
    @PostMapping("")
    public R<String> takeOrder(@RequestBody CreateOrderParams orderParams) throws ServiceException {
        return R.ok(orderService.createOrder(orderParams));
    }

    @ApiOperation("微信小程序预先支付")
    @NeedLogin
    @PostMapping("/pay/weixin")
    public R wxPrepay(@ApiParam String orderNo, @ApiParam String ip) throws ServiceException {
        return R.ok(orderService.wxPrepay(orderNo, ip));
    }

    /**
     * 接收支付返回的消息
     * @param
     */
    @ApiOperation(value="接收支付返回的消息")
    @PostMapping(value="/orderNotifyUrl")
    public String parseOrderNotifyResult(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("============支付回调开始");
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlResult);
            System.out.println(result.toString());
            // 结果正确
            String orderId = result.getOutTradeNo();
            String tradeNo = result.getTransactionId();
//            String totalFee = WxPayBaseResult.feeToYuan(result.getTotalFee());
            //自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
            System.out.println("============支付回调结束");
            return WxPayNotifyResponse.success("处理成功!");
        } catch (Exception e) {
            log.error("微信回调结果异常,异常原因{}" + e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }

    @ApiOperation("用户申请退款")
    @NeedLogin
    @PostMapping("/refund/{orderNo}")
    public R refund(@PathVariable String orderNo, String reason) throws ServiceException {
        return R.ok(orderService.refund(orderNo, reason));
    }

    @ApiOperation("取消订单")
    @NeedLogin
    @DeleteMapping("/cancel/{orderNo}")
    public R cancelOrder(@ApiParam("订单号") @PathVariable String orderNo) throws ServiceException {
        return R.ok(orderService.cancelOrder(orderNo));
    }

    @ApiOperation("确认收货")
    @ApiImplicitParam(name = "accessToken", value = "访问令牌", paramType = "header")
    @NeedLogin
    @PutMapping("/confirmReceive/{orderNo}")
    public R confirm(@ApiParam("订单号") @PathVariable String orderNo) throws ServiceException {
        return R.ok(orderService.finishedOrder(orderNo));
    }


    @ApiOperation("分页获取历史订单")
    @NeedLogin
    @GetMapping("/history/page/{pageNo}/{pageSize}")
    public R<Page<HistoryOrderVO>> getHistoryOrderByPage(@PathVariable Integer pageNo,
                                                         @PathVariable Integer pageSize) throws ServiceException {
        return R.ok(orderService.getHistoryOrderByPage(pageNo, pageSize));
    }

    @ApiOperation("订单详情信息")
    @GetMapping("/detail/{orderNo}")
    public R<OrderInfoDTO> getOrderDetail(@PathVariable String orderNo) throws ServiceException {
        return R.ok(orderService.getOrderDetail(orderNo));
    }

    @ApiOperation("获取正在处理的订单列表")
    @NeedLogin
    @GetMapping("/notCompleted")
    public R<List<OrderInfoDTO>> getHandlingOrders() throws ServiceException {
        return R.ok(orderService.getHandlingOrders());
    }
}
